package com.java110.mall.acct.cmd.payment;

import com.alibaba.fastjson.JSONObject;
import com.java110.core.annotation.Java110Cmd;
import com.java110.core.context.ICmdDataFlowContext;
import com.java110.core.event.cmd.Cmd;
import com.java110.core.event.cmd.CmdEvent;
import com.java110.dto.payment.PaymentOrderDto;
import com.java110.mall.acct.payment.IPaymentFactoryAdapt;
import com.java110.utils.cache.CommonCache;
import com.java110.utils.exception.CmdException;
import com.java110.utils.factory.ApplicationContextFactory;
import com.java110.utils.util.Assert;
import com.java110.utils.util.BeanConvertUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;

import java.util.Map;

@Java110Cmd(serviceCode = "payment.nativeQrcodePayment")
public class WechatNativeQrcodePaymentCmd extends Cmd {
    private static Logger logger = LoggerFactory.getLogger(WechatNativeQrcodePaymentCmd.class);

    private IPaymentFactoryAdapt paymentFactoryAdapt;

    @Override
    public void validate(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        Assert.hasKeyAndValue(reqJson, "money", "未包含支付金额");
        Assert.hasKeyAndValue(reqJson, "orderId", "未包含订单编号");
    }

    @Override
    public void doCmd(CmdEvent event, ICmdDataFlowContext cmdDataFlowContext, JSONObject reqJson) throws CmdException {
        PaymentOrderDto paymentOrderDto = BeanConvertUtil.covertBean(reqJson, PaymentOrderDto.class);
        paymentOrderDto.setOrderId(paymentOrderDto.getOrderId());
        paymentFactoryAdapt = ApplicationContextFactory.getBean("wechatNativeQrcodePaymentFactory", IPaymentFactoryAdapt.class);
        Map result = null;
        try {
            result = paymentFactoryAdapt.java110Payment(paymentOrderDto, reqJson, cmdDataFlowContext);
        } catch (Exception e) {
            logger.error("生成支付码异常", e);
            throw new CmdException(e.getLocalizedMessage());
        }
        ResponseEntity<String> responseEntity = new ResponseEntity<String>(JSONObject.toJSONString(result), HttpStatus.OK);
        cmdDataFlowContext.setResponseEntity(responseEntity);
        CommonCache.setValue("nativeQrcodePayment_" + paymentOrderDto.getOrderId(), reqJson.toJSONString(), CommonCache.PAY_DEFAULT_EXPIRE_TIME);
    }
}
